﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Devsoft.Utilities.Extentions
{
    public static class DictionaryExtension
    {
        //Get any value which is associated with given keys
        public static V GetAny<K,V>(this Dictionary<K,V> dict, params K[] keys)
        {
            foreach (var key in keys)
            {
                if (dict.ContainsKey(key))
                {
                    return dict[key];
                }
            }
            string msg = string.Format("The dictionary does not contain any given key in [{0}]",
                                       string.Join(", ", keys.Select(k => k.ToString())));
            throw new Exception(msg);
        }

        public static V GetAnyOrDefault<K, V>(this Dictionary<K, V> dict,V defaultVal, params K[] keys)
        {
            foreach (var key in keys)
            {
                if (dict.ContainsKey(key))
                {
                    return dict[key];
                }
            }
            return defaultVal;
        }


        public static V GetOrDefault<K, V>(this Dictionary<K, V> dict, K key,V val = default (V))
        {
            return dict.ContainsKey(key) ? dict[key] : val;
        }

        public static Dictionary<K, V>  MergesWith<K, V>(this Dictionary<K, V> dict,Dictionary<K, V> other,bool preferredOthers = true)
        {
            if (dict == null)
            {
                return other;
            }
            if (other == null)
            {
                return dict;
            }
            if (preferredOthers)
            {
                foreach (var kv in other)
                {
                    dict[kv.Key] = kv.Value;
                }
            }
            else
            {
                foreach (var kv in other.Where(x=>!dict.ContainsKey(x.Key)))
                {
                    dict[kv.Key] = kv.Value;
                }
            }
            return dict;
        }

    }
}
